package com.levi.service.impl;

import com.TestRegistryPostProcessor;
import com.levi.domain.User;
import com.levi.holder.ThreadLocalHodler;
import com.levi.service.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;


/**
 * @author shentong
 * @since 2022/6/22 10:13 PM
 */
@Slf4j
@Service
public class CommonServiceImpl implements CommonService {

	@Autowired
	private TestRegistryPostProcessor testRegistryPostProcessor;

	@Autowired
	private TransactionTemplate transactionTemplate;

	@Override
	public void testThreadLocalHolder() {
		testRegistryPostProcessor.setName("张三");
		Object o = ThreadLocalHodler.holder.get();
		if (o instanceof User) {
			User user = (User) o;
			log.info("commonService user :===>{}", user);
		}
	}

	/**
	 * 手动创建代理对象
	 * 1.导入aspectjweaver 依赖
	 * 2.启动类添加@EnableAspectJAutoProxy(exposeProxy = true)
	 * 3.使用AopContext.currentProxy()创建代理对象
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void decreStock() {
		System.out.println("扣减库存");

		//下订单   直接调用是this.createOrder(),没有走代理对象，所以createOrder方法的事务不会生效,要使用代理对象
		//createOrder();
		CommonService commonService = (CommonService) AopContext.currentProxy();
		commonService.createOrder();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void createOrder() {
		log.info("开始下单");
		//sendSms();
		log.info("下单完成");

	}

	/**
	 * 编程式事务
	 */
	public void testTransaction() {
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {

			}
		});
	}



	@Override
	@Async
	public void sendSms() {
		log.info("sendSms>>>>>>>>>>>");
	}



}
